//
//  CalendarViewController.m
//  leo
//
//  Created by 张旭 on 15/10/21.
//  Copyright © 2015年 mdx. All rights reserved.
//

#import "CalendarViewController.h"

@interface CalendarViewController (){
    NSMutableDictionary *_eventsByDate;
    
    NSDate *_dateSelected;
}
@property (strong, nonatomic) DataManager *dataManager;
@property(nonatomic,retain) User *user;
@property(nonatomic,retain) Watch *selectWatch;
@end

@implementation CalendarViewController
@synthesize motherWindow;
@synthesize calendarView;
@synthesize dateSelected;
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initBackGround];
    // Do any additional setup after loading the view, typically from a nib.
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
//  _calendarManager.dateHelper.calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh_Hans"];
    _calendarManager.dateHelper.calendar.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    // Generate random events sort by date using a dateformatter for the demonstration
    //[self createRandomEvents];
    self.dataManager = [[DataManager alloc] init];  // Zeming
    self.user=[User sharedSingleton];
    self.selectWatch=[self.dataManager getActiveWatch:self.user.uid];
    [self getEventsFromDB];
    [_calendarManager setMenuView:_calendarMenuView];
    [_calendarManager setContentView:_calendarContentView];
    [_calendarMenuView setUserInteractionEnabled:NO];
    [_calendarContentView setScrollEnabled:YES];
    [_calendarManager setDate:self.dateSelected];
}

- (void)initBackGround{
    [self.view setFrame:[UIScreen mainScreen].bounds];
    [self.view setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.4]];
    calendarView.layer.cornerRadius = 8;
    _calendarMenuView.layer.cornerRadius = 8;
    _calendarContentView.layer.cornerRadius = 8;

    UITapGestureRecognizer *tapReconizerToDismiss = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissView:)];
    [self.view addGestureRecognizer:tapReconizerToDismiss];
}

- (void)dismissView:(UITapGestureRecognizer *)tap
{
    motherWindow.hidden = YES;
}

#pragma mark - Buttons callback
- (IBAction)didGoTodayTouch:(id)sender {
    // 翻页动画效果
    [_calendarManager setDate:self.dateSelected];
}

#pragma mark - CalendarManager delegate

// Exemple of implementation of prepareDayView method
// Used to customize the appearance of dayView
- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    if([_calendarManager.dateHelper date:self.dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor colorWithRed:59.0/255 green:161.0/255 blue:244.0/255 alpha:1];
        dayView.dotView.backgroundColor = [UIColor greenColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
        //if (_dateSelected && [self haveEventForDay:dayView.date]) {
        if (_dateSelected) {
            motherWindow.hidden = YES;
            NSLog(@"CalendarViewController: %@", _dateSelected);
            
            NSDictionary *dataDict = [NSDictionary dictionaryWithObject:_dateSelected forKey:@"dateSelected"];  // Zeming
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectDateFromCalendar" object:nil userInfo:dataDict]; // Zeming
        }
    }
    // Selected date
    else if(_dateSelected && [_calendarManager.dateHelper date:_dateSelected isTheSameDayThan:dayView.date]){
        dayView.circleView.hidden = NO;
        dayView.circleView.backgroundColor = [UIColor redColor];
        //dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
        //TODO
//        if ([self haveEventForDay:dayView.date]) {
            motherWindow.hidden = YES;
            NSLog(@"CalendarViewController: %@", _dateSelected);

            NSDictionary *dataDict = [NSDictionary dictionaryWithObject:_dateSelected forKey:@"dateSelected"];  // Zeming
            [[NSNotificationCenter defaultCenter] postNotificationName:SELECTDATEFROMCALENDAR object:nil userInfo:dataDict]; // Zeming
//        }
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        dayView.circleView.hidden = YES;
      dayView.dotView.backgroundColor = [UIColor greenColor];
      dayView.textLabel.textColor = [UIColor lightGrayColor];
        //dayView.dotView.hidden = YES;
        //dayView.textLabel.hidden = YES;
        dayView.userInteractionEnabled = YES;
    }
    // Another day of the current month
    else{
        dayView.circleView.hidden = YES;
        dayView.dotView.backgroundColor = [UIColor greenColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date]){
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
    
    // 哪天有事件，做判断
    //dayView.dotView.hidden = NO;
}

- (void)calendar:(JTCalendarManager *)calendar didTouchDayView:(JTCalendarDayView *)dayView
{
    _dateSelected = dayView.date;
    
    // Animation for the circleView
    dayView.circleView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.1, 0.1);
    [UIView transitionWithView:dayView
                      duration:.3
                       options:0
                    animations:^{
                        dayView.circleView.transform = CGAffineTransformIdentity;
                        [_calendarManager reload];
                    } completion:nil];
    
    
    // Load the previous or next page if touch a day from another month
    
    if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
        if([_calendarContentView.date compare:dayView.date] == NSOrderedAscending){
            [_calendarContentView loadNextPageWithAnimation];
        }
        else{
            [_calendarContentView loadPreviousPageWithAnimation];
        }
    }
}

#pragma mark - Views customization

- (void)calendar:(JTCalendarManager *)calendar prepareMenuItemView:(UILabel *)menuItemView date:(NSDate *)date
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy年 MM月";
        
        dateFormatter.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    
    menuItemView.text = [dateFormatter stringFromDate:date];
    menuItemView.textColor = [UIColor colorWithRed:82.0/255 green:171.0/255 blue:245.0/255 alpha:1];
}

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}

- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
    
}

- (void)createRandomEvents
{
    _eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!_eventsByDate[key]){
            _eventsByDate[key] = [NSMutableArray new];
        }
        
        [_eventsByDate[key] addObject:randomDate];
    }
}

- (void)getEventsFromDB
{
    int year = [[self NSDateToString:self.dateSelected withFormatter:@"yyyy"] intValue];
    int month = [[self NSDateToString:self.dateSelected withFormatter:@"MM"] intValue];
    int lastYear = (month == 1) ? (year - 1) : year;
    int nextYear = (month == 12) ? (year + 1) : year;
    int lastMonth = (month == 1) ? 12 : (month + 1);
    int nextMonth = (month == 12) ? 1 : (month - 1);
    
    NSLog(@"Now the time is: %d-%d-%d %d:%d:%d", year, month, [[self NSDateToString:self.dateSelected withFormatter:@"dd"] intValue], [[self NSDateToString:self.dateSelected withFormatter:@"HH"] intValue], [[self NSDateToString:self.dateSelected withFormatter:@"mm"] intValue], [[self NSDateToString:self.dateSelected withFormatter:@"ss"] intValue]);
    
    _eventsByDate = [NSMutableDictionary new];
    
    NSArray *lastEventArray = [self.dataManager getMonthLocData:lastYear month:lastMonth deviceUid:self.selectWatch.deviceUid];
    NSArray *eventArray = [self.dataManager getMonthLocData:year month:month deviceUid:self.selectWatch.deviceUid];
    NSArray *nextEventArray = [self.dataManager getMonthLocData:nextYear month:nextMonth deviceUid:self.selectWatch.deviceUid];
    
    for(int i = 1; i < 32; i++){
        if ([eventArray[i] intValue] == 1 || [lastEventArray[i] intValue] == 1 || [nextEventArray[i] intValue] == 1) {
            NSString *str;
            
            if ([eventArray[i] intValue] == 1) {
                str = [self getDateStringWithYear:year Month:month andDay:i];
            }
            if ([lastEventArray[i] intValue] == 1) {
                str = [self getDateStringWithYear:lastYear Month:lastMonth andDay:i];
            }
            if ([nextEventArray[i] intValue] == 1) {
                str = [self getDateStringWithYear:nextYear Month:nextMonth andDay:i];
            }
            
            NSDate *eventDate = [self stringformat2NSDate:str withFormatter:@"yyyyMMdd"];
            NSLog(@"yearMonthDay: %@", eventDate);
            
            // Use the date as key for eventsByDate
            NSString *key = [[self dateFormatter] stringFromDate:eventDate];
            NSLog(@"key[%i] = %@", i, key);
            
            if(!_eventsByDate[key]){
                _eventsByDate[key] = [NSMutableArray new];
            }
            
            [_eventsByDate[key] addObject:eventDate];
        }
    }
}

- (NSString *)getDateStringWithYear:(int)year Month:(int)month andDay:(int)day
{
    NSString *yearStr = [NSString stringWithFormat:@"%i", year];
    NSString *monthStr = month >= 10 ? [NSString stringWithFormat:@"%i", month] : [@"0" stringByAppendingString:[NSString stringWithFormat:@"%i", month]];
    NSString *dayStr = day >= 10? [NSString stringWithFormat:@"%i", day] : [@"0" stringByAppendingString:[NSString stringWithFormat:@"%i", day]];
    
    return [[yearStr stringByAppendingString:monthStr] stringByAppendingString:dayStr];
}

- (NSDate *)stringformat2NSDate:(NSString *)str withFormatter:(NSString *)formatter
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:formatter];
    
    return [dateFormatter dateFromString:str];
}

- (NSString *)NSDateToString:(NSDate *)date withFormatter:(NSString *)formatter
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:formatter];
    
    return [dateFormatter stringFromDate:date];
}
@end
